package com.zhihaoliang.moshi.biz.io

import android.content.Context
import com.squareup.moshi.Moshi
import com.zhihaoliang.moshi.util.log
import okio.buffer
import okio.sink
import java.io.File
import java.io.FileOutputStream


/**
 * @author 支豪亮
 * @date 2023/1/20 15:46
 * @des Any 转化的 Json 数据流
 */


fun <T> outStream(obj: T, context: Context) {
    val file = File(context.cacheDir, "textKotlin.txt")
    if (!file.exists()) file.createNewFile()
    log("${file.absolutePath} : ${file.exists()}")
    val fileOutputStream = FileOutputStream(file)
    val moshi = Moshi.Builder().build()

    val adapter = moshi.adapter(obj!!::class.java as Class<T>?) //根据泛型获取adapter

    val out = fileOutputStream.sink().buffer() //OutputStream 转化为 Sink.buffer
    adapter.toJson(out, obj) //对象数据的写入

    out.flush()
    log("kotlin end")
}
